package com.ssish.saas.eccs.schedule;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.github.pagehelper.util.StringUtil;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.SftpException;
import com.ssish.saas.eccs.mapper.ClaimsAssessmentMapper;
import com.ssish.saas.eccs.mapper.ClaimsMapper;
import com.ssish.saas.eccs.mapper.ClaimsVoMapper;
import com.ssish.saas.eccs.mapper.EmployeeMapper;
import com.ssish.saas.eccs.mapper.EmployeeVoMapper;
import com.ssish.saas.eccs.mapper.EspTxtexpMapper;
import com.ssish.saas.eccs.mapper.EspTxtexpsummMapper;
import com.ssish.saas.eccs.mapper.MmtIclaimMapper;
import com.ssish.saas.eccs.mapper.PayorMapper;
import com.ssish.saas.eccs.mapper.PayorProviderMappingMapper;
import com.ssish.saas.eccs.mapper.ProviderMapper;
import com.ssish.saas.eccs.mapper.RsvamtTrackingMapper;
import com.ssish.saas.eccs.mapper.SycRefcdMapper;
import com.ssish.saas.eccs.mapper.SycRefcdVoMapper;
import com.ssish.saas.eccs.model.ClaimsAssessment;
import com.ssish.saas.eccs.model.ClaimsAssessmentExample;
import com.ssish.saas.eccs.model.Employee;
import com.ssish.saas.eccs.model.EmployeeExample;
import com.ssish.saas.eccs.model.EspTxtexp;
import com.ssish.saas.eccs.model.EspTxtexpsumm;
import com.ssish.saas.eccs.model.MmtIclaim;
import com.ssish.saas.eccs.model.MmtIclaimExample;
import com.ssish.saas.eccs.model.Payor;
import com.ssish.saas.eccs.model.PayorExample;
import com.ssish.saas.eccs.model.PayorProviderMapping;
import com.ssish.saas.eccs.model.PayorProviderMappingExample;
import com.ssish.saas.eccs.model.Provider;
import com.ssish.saas.eccs.model.ProviderExample;
import com.ssish.saas.eccs.model.RsvamtTracking;
import com.ssish.saas.eccs.model.RsvamtTrackingExample;
import com.ssish.saas.eccs.model.SycRefcd;
import com.ssish.saas.eccs.model.SycRefcdExample;
import com.ssish.saas.eccs.util.SFTPUtil;
import com.ssish.saas.eccs.util.TiffUtil;
import com.ssish.saas.eccs.vo.ClaimsVo;
import com.ssish.saas.eccs.vo.SycRefcdVo;

/**
 * 中华联合
 * 
 * @author EDZ
 * @date 2020年1月2日
 */
@Service("zhlhJob")
public class ZhlhJob {
    
    @Autowired
    private ClaimsMapper claimsMapper;
    
    @Autowired
    private EspTxtexpMapper espTxtexpMapper;
    
    @Autowired
    private EspTxtexpsummMapper espTxtexpsummMapper;
    
    @Autowired
    private RsvamtTrackingMapper rsvamtTrackingMapper;
    
    @Autowired
    private ClaimsVoMapper claimsVoMapper;
    
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeVoMapper employeeVoMapper;
    
    @Autowired
    private PayorMapper payorMapper;
    
    @Autowired
    private SycRefcdMapper sycRefcdMapper;
    
    @Autowired
    private ProviderMapper providerMapper;
    
    @Autowired
    private PayorProviderMappingMapper payorProviderMappingMapper;
    
    
    @Autowired
    private ClaimsAssessmentMapper claimsAssessmentMapper;
    
    @Autowired
    private SycRefcdVoMapper sycRefcdVoMapper;
    
    @Autowired
    private MmtIclaimMapper mmtIclaimMapper;
    
    
    
    
    private static final String PAYORCD = "PAJK008";
    
    public Date date = null;
    public static final String P_CURRUSR = "SYSTEM_SH";
    
    // 责任层
    public static final String CHF = "CHF";
    // 费用层
    public static final String CDF = "CDF";
    // 受益人&领款人
    public static final String BNF = "BNF";
    // 影像信息
    public static final String IMG = "IMG";
    // 第三方支付
    public static final String COV = "COV";
    // 诊断类型
    public static final String DIAG = "DIAG";
    
    public Integer v_clcnterr ;
    
    
    public static String accessKeyId = "LTAINbgTZ6PA6bLd";
    public static String accessKeySecret = "xbTMcpICuaGihpWhkIjWp2c2hpJUdr";
    public static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    public static String bucketName = "test-ssish";
    public static String prefix = "medilink/mdlcnpro/ClaimsDocument/";
    // 中华联合NewMissions 目录
    public static String ZHLH_PATH = "";
    public static String NY_PATH = "/CICLTEST";
    
    @Value(value = "${zh.sftp.url}")
    public String ZH_SFTP_URL;
    @Value(value = "${zh.sftp.user}")
    public String ZH_SFTP_USER;
    @Value(value = "${zh.sftp.password}")
    public String ZH_SFTP_PASSWORD;
    @Value(value = "${ny.sftp.url}")
    public String NY_SFTP_URL;
    @Value(value = "${ny.sftp.user}")
    public String NY_SFTP_USER;
    @Value(value = "${ny.sftp.password}")
    public String NY_SFTP_PASSWORD;
    
    public void test(){
     // 中华联合FTP
//        SFTPUtil sftpZH = new SFTPUtil(ZH_SFTP_USER, ZH_SFTP_PASSWORD, ZH_SFTP_URL, 22);// 2.0开发环节测试
        SFTPUtil sftpZJD = new SFTPUtil(NY_SFTP_USER, NY_SFTP_PASSWORD, NY_SFTP_URL, 22);// 2.0开发环节测试

        sftpZJD.login();
        System.out.println("success");

        try {
            Vector<?> files = sftpZJD.listFiles("/");
            files.forEach(e -> System.out.println(e.toString()));
        } catch (SftpException e) {
            System.out.println("error" + e.getStackTrace());
            // TODO Auto-generated catch block
             e.printStackTrace();
        }
        sftpZJD.logout();
    }
    
    /**
     * (3) 保单信息导入：外包商定期从SFTP服务器获取保单承保信息，以及每日生成的保全变更信息， 
     * 并在外包商的IT系统中做相应配置和更新。若对上述信息存在疑问，应及时与中华联合确认相关问题并重新获取文件。
     */
     @Scheduled(cron = "${job.scheduled}")
    public void run() {
        // 中华联合FTP
        SFTPUtil sftpZH = new SFTPUtil(ZH_SFTP_USER, ZH_SFTP_PASSWORD, ZH_SFTP_URL, 22);// 2.0开发环节测试
        // 中间带FTP
        SFTPUtil sftpZJD = new SFTPUtil(NY_SFTP_USER, NY_SFTP_PASSWORD, NY_SFTP_URL, 22);// 2.0开发环节测试

        // 从中华读取文件
        sftpZH.login();
        sftpZJD.login();
        
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy/MM/dd");
        try {
            Vector<?> files = sftpZH.listFiles(ZHLH_PATH+"/NewMissions");

            List<String> ret = new ArrayList<String>();
            for (int i = 0; i < files.size(); i++) {
                Object obj = files.elementAt(i);
                if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                    LsEntry entry = (LsEntry)obj;
                    if (true && !entry.getAttrs().isDir()) {
                        ret.add(entry.getFilename());
                    }
                    if (true && entry.getAttrs().isDir()) {
                        if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")) {
                            ret.add(entry.getFilename());
                        }
                    }
                }
            }

            for (String fileName : ret) {
                //
                InputStream in = sftpZH.downloadForStream(ZHLH_PATH+"/NewMissions", fileName);
                String directory = sf1.format(sf.parse(fileName.split("_")[1]));
                //
                sftpZJD.upload(NY_PATH, "", fileName, in);
                sftpZH.upload(ZHLH_PATH + "/NewMissionsBackup", directory, fileName, in);

                sftpZH.delete(ZHLH_PATH+"/NewMissions", fileName);
            }

        } catch (SftpException | IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        sftpZJD.logout();

        sftpZH.logout();

        System.out.println(new Date());
    }

    /**
     * (6)  案件处理结果返回：外包商处理完案件后，
     * 将案件数据上传至SFTP 文件服务器中对应目录，
     * 数据格式为TXT 文件（文件标准在附录中提供），
     * 一个批次赔案生成一个TXT 文件，中华联合系统每天定时自动执行导入。
     * 
     * 查询两张表
     * 插入到两张表中，同时写入到文件中
     * 报文文件命名规则：
        1.受益人&领款人信息报文文件的命名规则
        PAYORCD-BNF-YYMMDD-hh24miss-1.txt
        2.影像信息报文文件的命名规则
        PAYORCD-IMG-YYMMDD-hh24miss-1.txt
        3.第三方给付信息报文文件的命名规则
        PAYORCD-COV-YYMMDD-hh24miss-1.txt
        4.诊断类型信息报文文件的命名规则
        PAYORCD-DIAG-YYMMDD-hh24miss-1.txt
        5.责任层文件命名规则
        PAYORCD-CHF-YYMMDD-hh24miss-1.txt
        6.费用层文件名命名规则
        PAYORCD-CDF-YYMMDD-hh24miss-1.txt
     */
     @Scheduled(cron = "${job.scheduled.returndata}")
    public void run6() {
        ClaimsVo param = new ClaimsVo();
        date = new Date();
        v_clcnterr = 0;
        param.setPayorCode(PAYORCD);
        List<ClaimsVo> claimsList = claimsVoMapper.selectClaimsVo(param);
        
        SimpleDateFormat sf = new SimpleDateFormat("YYYYMMDD-HHmm");
        // 责任层
        StringBuilder sbCoverage = createCoverageFile(claimsList);

        // 费用层
        StringBuilder sbFei = createFeiFile(claimsList);

        // 受益人&领款人
        StringBuilder sbShouyi = createShouyiFile(claimsList);

        // 影像信息
        StringBuilder sbImage = createImageFile(claimsList);

        // 第三方支付
        StringBuilder sbOtherPay = createOtherPayFile(claimsList);

        // 诊断类型
        StringBuilder sbSecondary = createSecondaryFile(claimsList);

        SFTPUtil sftpZH = new SFTPUtil(ZH_SFTP_USER, ZH_SFTP_PASSWORD, ZH_SFTP_URL, 22);// 2.0开发环节测试
        sftpZH.login();
        upLoad(sbCoverage, PAYORCD + "-" + CHF + "-" + sf.format(date) + "-1.txt", sftpZH);
        upLoad(sbFei, PAYORCD + "-" + CDF + "-" + sf.format(date) + "-1.txt", sftpZH);
        upLoad(sbShouyi, PAYORCD + "-" + BNF + "-" + sf.format(date) + "-1.txt", sftpZH);
        upLoad(sbImage, PAYORCD + "-" + IMG + "-" + sf.format(date) + "-1.txt", sftpZH);
        upLoad(sbOtherPay, PAYORCD + "-" + COV + "-" + sf.format(date) + "-1.txt", sftpZH);
        upLoad(sbSecondary, PAYORCD + "-" + DIAG + "-" + sf.format(date) + "-1.txt", sftpZH);
        sftpZH.logout();
        for (ClaimsVo claim : claimsList) {
            updateRsvamtTracking(claim);
        }
        
    }
    
    /**
     *  责任层
     *  PAYORCD-CHF-YYMMDD-hh24miss-1.txt
     * @param claimList
     * 1,30352125,42187.33681,XXXX开放式股份公司北京代表处,北京平心堂中医门诊部,G100000000,G100000000-0000000004M,刘XX,刘XX,OP-TCM,N92,月经过多、频繁且不规则,1671.9,1671.9,0,40,1671.9,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
     */
    
    public StringBuilder createCoverageFile(List<ClaimsVo> claimsList) {
        StringBuilder sb = new StringBuilder();
        String errorMsg = "";
        SycRefcdExample sycRefcdExample = new SycRefcdExample();
        sycRefcdExample.or().andRefgrpEqualTo("CICL_ID_TYPE");
        List<SycRefcd> sycRefcdList = sycRefcdMapper.selectByExample(sycRefcdExample);
        Map<String, String> idTypeMap = sycRefcdList.stream()
                            .collect(Collectors.toMap(e -> e.getRefcd(), e -> e.getVar1()));
        
        DecimalFormat df = new DecimalFormat("0.00");
        int i = 1;
        for (ClaimsVo claim : claimsList) {
            // 序号
            sb.append(i);
            sb.append(",");
            // 中间带理赔号
            sb.append(claim.getClaimsId());

            // 就诊/入院日期   
            sb.append(claim.getAdmissionDate());
            sb.append(",");

            // 投保公司名称
            PayorExample payorExample = new PayorExample();
            payorExample.or().andPayorCodeEqualTo(claim.getPayorCode());
            List<Payor> payorList = payorMapper.selectByExample(payorExample);
            if(null != payorList&&payorList.size()>0){
                sb.append(payorList.get(0).getLongName());
            }
            sb.append(",");

            // 就诊医院名称
            sb.append(claim.getProviderName());
            sb.append(",");

            // 保单号
            sb.append(claim.getPolicyNo());
            sb.append(",");

            // 客户号 
            EmployeeExample employeeExample = new EmployeeExample();
            employeeExample.or().andMemberControlNoEqualTo(claim.getMemberControlNo());
            List<Employee> employeeList = employeeMapper.selectByExample(employeeExample);
            // 出险人
            Employee beneficiary = employeeList.get(0);
            if(null != employeeList&&employeeList.size()>0){
                sb.append(beneficiary.getPayorMemberId());
            }
            sb.append(",");

            // 出险人姓名
            if(null != employeeList&&employeeList.size()>0){
                sb.append(beneficiary.getEmpName());
            }
            sb.append(",");

            // 主被保险人姓名   和主被险人关系为0 且被保险人ID 等于主保人ID时 认为出险人同主被险人
            Employee employee = null;     
            if("0".equals(beneficiary.getRelationship())&&beneficiary.getMemberControlNo().equals(beneficiary.getEmployeeId())){
                employee = beneficiary;
            }else{
                employee = employeeVoMapper.selectEmployeeByMemberControlNo(claim.getMemberControlNo());   
            }
            sb.append(employee.getEmpName());
            sb.append(",");

            // 中间带的责任代码 TODO
            sb.append(StringUtil.isNotEmpty(claim.getCoverageId()) ? claim.getCoverageId() : "");
            sb.append(",");

            sycRefcdExample = new SycRefcdExample();
            sycRefcdExample.or().andRefgrpEqualTo("CICL_ICD_MAPPING").andRefcdEqualTo(claim.getPrimaryDiagnosis());
            sycRefcdList = sycRefcdMapper.selectByExample(sycRefcdExample);
            if(null != sycRefcdList&&sycRefcdList.size()>0){
                // 诊断代码 
                sb.append(sycRefcdList.get(0).getVar1());
                sb.append(",");
                
                // 诊断描述
                sb.append(sycRefcdList.get(0).getFdesc());
                sb.append(",");
            }else{
                sb.append(",");
                sb.append(",");
            }

            // 发生金额
            sb.append(null != claim.getDueTotal() ? claim.getDueTotal() : "");
            sb.append(",");

            // 赔付金额
            sb.append(null != claim.getPaidToClaimant() ? claim.getPaidToClaimant() : "");
            sb.append(",");

            // 自付额
            sb.append(null != claim.getPaidByClaimant() ? claim.getPaidByClaimant() : "");
            sb.append(",");

            // 中间带理赔状态
            sb.append(StringUtil.isNotEmpty(claim.getClaimsStatus()) ? claim.getClaimsStatus() : "");
            sb.append(",");

            // 本笔理赔财务结算金额 
            if(null != claim.getCurrrt()){
                sb.append(df.format(claim.getCurrrt().multiply(claim.getPaidToClaimant())));
            }
            sb.append(",");

            // TPA渠道编码 
            sb.append("0010");
            sb.append(",");

            // TPA业务类型 
            sb.append("13");
            sb.append(",");
            
            // 中间带理赔类型    
            if("R".equals(claim.getClaimType())){
                sb.append("1");
            }else if("E".equals(claim.getClaimType())||"M".equals(claim.getClaimType())){
                sb.append("0");
            }
            // 赔付金额 
            sb.append(claim.getPaidToClaimant());
            sb.append(",");

            // 备注
            sb.append(",");

            String provinceCode = "";
            String cityCode = "";
            String areaCode = "";
            if("E".equals(claim.getClaimType())||"M".equals(claim.getClaimType())){
                
                ProviderExample providerExample = new ProviderExample();
                providerExample.or().andProviderCodeEqualTo(claim.getProviderId());
                List<Provider> providerList = providerMapper.selectByExample(providerExample);
                if(null != providerList&&providerList.size()>0){
                    Provider provider = providerList.get(0);
                    String country = provider.getCountry();
                    String state = provider.getState();
                    String getDist = provider.getDist();
                    if("TWN".equals(country)||("TW".equals(state)&&"CHN".equals(country))){
                        provinceCode = "71";
                        cityCode = "7110";
                        areaCode = "711000";
                    }else if("HKG".equals(country)||("HK".equals(state)&&"CHN".equals(country))){
                        provinceCode = "81";
                        cityCode = "8110";
                        areaCode = "811000";
                    }else if("MAC".equals(country)||("MO".equals(state)&&"CHN".equals(country))){
                        provinceCode = "82";
                        cityCode = "8210";
                        areaCode = "821000";
                    }else if(!"CHN".equals(country)||claim.getProviderId().indexOf("NPK") > 0){
                        // TODO
//                        v_errmsg   := 'Provider is NPK ';
//                    v_clcnt    := v_clcnt - 1;
//                    v_clcnterr := v_clcnterr + 1;
//                    v_recnoerr := v_recnoerr + 1;
//                    claimserror(i.claims_id); --to insert error record into est_txtexp
//                    GOTO claimserr;
                    }else{
                        if(StringUtil.isEmpty(state)||StringUtil.isEmpty(getDist)){
                            // TODO error
                        }
                        Map<String, Object> param = new HashMap<String, Object>();
                        param.put("refgrp", "SINO_GEOGR_3");
                        SycRefcdVo sysRefcdVo = sycRefcdVoMapper.getAreaData(param);
                        
                        
                        if(null == sysRefcdVo){
                            param.put("refgrp", "SINO_GEOGR_2");

                            sysRefcdVo = sycRefcdVoMapper.getAreaData(param);
                        }
                        if(null == sysRefcdVo){
                            // TODO nodata
                        }
                        
                        
                        
                        
                        
                    }
                    
                    
                    
                }
                
            }else{
                MmtIclaimExample mmtIclaimExample = new MmtIclaimExample();
                mmtIclaimExample.or().andIclaimidEqualTo(claim.getSystrc());
                List<MmtIclaim> mmtIclaimList = mmtIclaimMapper.selectByExample(mmtIclaimExample);
                if(null != mmtIclaimList&&mmtIclaimList.size()>0){
                    MmtIclaim mmtIclaim = mmtIclaimList.get(0);
                    provinceCode = mmtIclaim.getProviderCode().substring(0, 2);
                    cityCode = mmtIclaim.getCityCode().substring(0, 4);
                    areaCode = mmtIclaim.getDistrictCode();
                }
            }
           // 出险地点(省 )
           sb.append(provinceCode);
           sb.append(",");

            
           // 出险地点(地级)
           sb.append(cityCode);
           sb.append(",");

           // 出险地点(县区)
           sb.append(areaCode);
           sb.append(",");
            
            // 出险人地址
            sb.append(",");

            // 出险原因  TODO
            sb.append(",");

            // 意外细节
            sb.append(",");

            // 出险结果
            sb.append(",");

            // 治疗医院编码
            sb.append(",");

            // 治疗情况
            sb.append(",");

            // 理赔类型 
            sb.append("00"); // 默认00
            sb.append(",");

            // 出险人姓名
            sb.append(beneficiary.getEmpName());
            sb.append(",");

            // 出险人性别
            sb.append("M".equals(beneficiary.getGender())?"0":"F".equals(beneficiary.getGender())?"1":"2");
            sb.append(",");

            // 出险人证件类型
            sb.append(idTypeMap.get(beneficiary.getIdType()));
            sb.append(",");

            // 出险人证件号码
            sb.append(idTypeMap.get(beneficiary.getNewIc()));
            sb.append(",");

            // 出险人证件有效期
            sb.append(",");

            // 出险人国籍
            sb.append(",");

            // 出险人职业
            sb.append(",");

            // 出险人住所地址（省）
            sb.append(",");

            // 出险人住所地址（市）
            sb.append(",");

            // 出险人住所地址（区/县）
            sb.append(",");

            // 出险人住所地址（街道）
            sb.append(",");

            // 出险人与主被保险人关系
            String relationships = getRelationships(beneficiary);
            sb.append(relationships);
            sb.append(",");

            // 出险人电话
            sb.append(",");

            // 出险人手机
            sb.append(",");

            // 出险人邮箱
            sb.append(",");

            // 出险人邮编
            sb.append(",");

            // 险种代码
            sb.append("G0019A");
            sb.append(",");

            // 险种赔付金额    1480
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("claimsId", claim.getClaimsId());
            param.put("systrc", claim.getSystrc());
            param.put("claimType", claim.getClaimType());
            param.put("payorCode", "CTPD014");
            String v_LLClaimRealPay = "0.00";
            try{
                v_LLClaimRealPay = employeeVoMapper.getPlanPaidToClaimant(param);
            }catch(Exception e){
                e.printStackTrace();
            }
            sb.append(v_LLClaimRealPay);
            sb.append(",");

            // 审核结论  m赔付金额大于0 
            if(Double.parseDouble(v_LLClaimRealPay)<=0){
                sb.append("1");
                sb.append(",");
                
                // 拒付原因
                String auditNoPassReason = claim.getReferredopformno();
                if(StringUtils.isEmpty(auditNoPassReason)&&("22".equals(claim.getClaimsStatus())||"43".equals(claim.getClaimsStatus()))){
                    auditNoPassReason = "11";
                }
                sb.append(auditNoPassReason);
                sb.append(claim.getRemarks());
                sb.append(",");
                
                // 拒付描述
                sb.append(claim.getRemarks());
                sb.append(",");
            }else{
                sb.append("0");
                sb.append(",");
                
                // 拒付原因
                sb.append(",");
                
                // 拒付描述
                sb.append(",");
            }

            // 审核意见描述
            sb.append(StringUtils.isNotBlank(claim.getRemarks())?claim.getRemarks():"赔付");
            sb.append(",");

            RsvamtTrackingExample rsvamtTrackingExample = new RsvamtTrackingExample();
            
            rsvamtTrackingExample.or().andClaimsIdEqualTo(claim.getClaimsId()).andClaimsStatusEqualTo("58");
            rsvamtTrackingExample.setOrderByClause("approved_date desc");
            List<RsvamtTracking> rsvamtTrackingList = rsvamtTrackingMapper.selectByExample(rsvamtTrackingExample);
            if(null != rsvamtTrackingList&&rsvamtTrackingList.size()>0){
                // 审核人 
                sb.append(rsvamtTrackingList.get(0).getApprovedBy());
                sb.append(",");
                // 审核时间
                sb.append(rsvamtTrackingList.get(0).getApprovedDate());
                sb.append(",");
            }else{
                // TODO error
                sb.append(",");
                sb.append(",");
            }


            // 签批结论 TODO 
            sb.append(",");

            // 签批不通过原因
            sb.append(",");

            // 签批不通过描述
            sb.append(",");

            // 签批意见描述
            sb.append(",");

            
            rsvamtTrackingExample = new RsvamtTrackingExample();
            
            rsvamtTrackingExample.or().andClaimsIdEqualTo(claim.getClaimsId()).andClaimsStatusEqualTo("56").andDefercdEqualTo("25");
            rsvamtTrackingExample.setOrderByClause("approved_date desc");
            rsvamtTrackingList = rsvamtTrackingMapper.selectByExample(rsvamtTrackingExample);
            if(null != rsvamtTrackingList&&rsvamtTrackingList.size()>0){
                // 签批人
                sb.append(rsvamtTrackingList.get(0).getApprovedBy());
                sb.append(",");
                // 签批时间
                sb.append(rsvamtTrackingList.get(0).getApprovedDate());
            }else{
                sb.append(",");
            }
            sb.append("\n");
            claimserror(claim.getClaimsId(), true, errorMsg, CHF);
        }
        return sb;

        
    }
    
    /**
     * 费用层
     */
    public StringBuilder createFeiFile(List<ClaimsVo> claimsList){
        
        
        StringBuilder sb = new StringBuilder();
        String errorMsg = "";
        for (ClaimsVo claim : claimsList) {
            // 客户号             
            EmployeeExample employeeExample = new EmployeeExample();
            employeeExample.or().andMemberControlNoEqualTo(claim.getMemberControlNo());
            List<Employee> employeeList = employeeMapper.selectByExample(employeeExample);
            Employee beneficiary = employeeList.get(0);
            if(null == employeeList||employeeList.size()==0){
                errorMsg = "客户号为空！";
                continue;
            }
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("claimsId", claim.getClaimsId());
            param.put("payorCode", PAYORCD);
            
            List<SycRefcdVo> sycRefcdList = sycRefcdVoMapper.getBenefitCodeList(param);
            if(null == sycRefcdList||sycRefcdList.size()==0){
                errorMsg = "费用信息为空！";
                claimserror(claim.getClaimsId(), true, errorMsg, CDF);
                continue;
            }
            // 医院代码
            String payorProviderCode = "00004145";
            if(null != claim.getProviderName()){
                PayorProviderMappingExample payorProviderMappingExample = new PayorProviderMappingExample();
                payorProviderMappingExample.or().andPayorCodeEqualTo(PAYORCD).andPayorProviderNameEqualTo(claim.getProviderName().toString());
                List<PayorProviderMapping> payorProviderMappingList = payorProviderMappingMapper.selectByExample(payorProviderMappingExample);
                
                if(null != payorProviderMappingList&&payorProviderMappingList.size()>0){
                    payorProviderCode = payorProviderMappingList.get(0).getPayorProviderCode();
                }
            }
            
            for(SycRefcdVo sycRefcdVo:sycRefcdList){
                
                // 中间带理赔号          
                sb.append(claim.getClaimsId());
                sb.append(",");
                sb.append(beneficiary.getPayorMemberId());
                sb.append(",");
                // 分公司代码            
                sb.append(claim.getCentreCode());
                sb.append(",");
                // 就诊类型              
                if("OP".equals(claim.getAdmissionType())){
                    sb.append("A"); 
                }else if("IP".equals(claim.getAdmissionType())){
                    sb.append("B");
                }
                sb.append(",");
                // 我司费用代码
                sb.append(sycRefcdVo.getBenefitCode());
                sb.append(",");
                // 就诊/入院日期         
                sb.append(claim.getAdmissionDate());
                sb.append(",");
                // 出院日期          
                sb.append(claim.getDischargeableDate());
                sb.append(",");
                // 单项费用发生金额     
                sb.append(sycRefcdVo.getAmtIncurred());
                sb.append(",");
                // 单项费用的自负额   
                sb.append(sycRefcdVo.getAmtToPay());
                sb.append(",");
                // 单项费用的赔付额      
                sb.append(sycRefcdVo.getAmtIncurred());
                sb.append(",");
//                // 中间带理赔类型    
//                if("R".equals(claim.getClaimType())){
//                    sb.append("1");
//                }else if("E".equals(claim.getClaimType())||"M".equals(claim.getClaimType())){
//                    sb.append("0");
//                }
                sb.append(",");
                // 单证类型             
                String admissionType = claim.getAdmissionType();
                String coverageId = claim.getCoverageId();
                if("OP".equals(admissionType)){
                    if("OP-MAT".equals(coverageId)){
                        sb.append("3");
                    }else{
                        sb.append("1");
                    }
                }else if("IP".equals(admissionType)){
                    if("MAT".equals(coverageId)){
                        sb.append("5");
                    }else{
                        sb.append("3");
                    }
                }
                sb.append(",");
                // 收据编号            
                if("R".equals(claim.getClaimType())){
                    sb.append(claim.getInvoiceId());
                }else if("E".equals(claim.getClaimType())||"M".equals(claim.getClaimType())){
                    sb.append(claim.getClaimsId());
                }
                sb.append(",");
                // 医院代码  
                sb.append(payorProviderCode);
                sb.append(",");
                // 单证发生金额 
                sb.append(claim.getDueTotal());
                sb.append(",");
                // 医疗保险范围内金额 
                sb.append("0.00");
                sb.append(",");
                // 医疗保险基金支付金额 
                sb.append("0.00");
                sb.append(",");
                // 其中起付金额 
                
                sb.append(",");
                // 其中超大额封顶金额
                
                sb.append(",");
                // 扣减费用类型          
                
                sb.append(",");
                // 扣费比例              
                
                sb.append(",");
                // 费用扣减金额          
              sb.append(",");

                
             // 给付责任代码  TODO 1717 
//              如果案件的Coverage_id是H&S ,并且案件的Benefit_code不包含130的时候取019E66
//              如果案件的Coverage_id是H&S ,并且案件的Benefit_code包含130的时候取019E67
//              如果案件的Coverage_id是H&S并且案件的Benefit_code包含112,148,129,198,185,18或者案件的Coverage_id是GP并且案件的Benefit_code包含125,122,123 的时候取019E68
              
              sb.append(",");
              // 给付类型  
              String payType = "";
              if("22".equals(claim.getClaimsStatus())||"43".equals(claim.getClaimsStatus())){
                  payType = "1";
              }else if("40".equals(claim.getClaimsStatus())){
                  
                  ClaimsAssessmentExample claimsAssessmentExample = new ClaimsAssessmentExample();
                  claimsAssessmentExample.or().andClaimsIdEqualTo(claim.getClaimsId()).andBenefitCodeEqualTo("26");
                  List<ClaimsAssessment> claimsAssessmentList = claimsAssessmentMapper.selectByExample(claimsAssessmentExample);
                  if(null != claimsAssessmentList&&claimsAssessmentList.size()>0){
                      payType = "2";
                  }else{
                      payType = "0";
                  }
              }
              sb.append(payType);
              sb.append(",");
              // 拒付原因代码
              sb.append(",");
              // 发票总金额 总金额（拆后）
              sb.append(claim.getDueTotal());
              sb.append(",");
              // 免赔额
              sb.append(claim.getDeductible());
              sb.append(",");
              // 核算赔付金额
              sb.append(claim.getPaidToClaimant());
              sb.append(",");
              // 通融赔付  TODO 需要重新查询
              if("2".equals(payType)){
                  sb.append(claim.getPaidToClaimant());
              }
              sb.append(",");
              // 协议赔付
              sb.append(",");
              // 赔付金额
              sb.append(claim.getPaidToClaimant());
            sb.append("\n");
            claimserror(claim.getClaimsId(), true, errorMsg, CDF);
            }
        }
        return sb;
    }
    
    /**
     * 受益人&领款人
     */
    public StringBuilder createShouyiFile(List<ClaimsVo> claimsList) {

        StringBuilder sb = new StringBuilder();
        String errorMsg = "";

        // 证件类型
        SycRefcdExample sycRefcdExample = new SycRefcdExample();
        sycRefcdExample.or().andRefgrpEqualTo("CICL_ID_TYPE");
        List<SycRefcd> sycRefcdList = sycRefcdMapper.selectByExample(sycRefcdExample);
        Map<String, String> idTypeMap = sycRefcdList.stream()
                            .collect(Collectors.toMap(e -> e.getRefcd(), e -> e.getVar1()));
        
        for (ClaimsVo claim : claimsList) {
            EmployeeExample example = new EmployeeExample();
            example.or().andMemberControlNoEqualTo(claim.getMemberControlNo());
            List<Employee> empList = employeeMapper.selectByExample(example);
            if (null == empList || empList.size() == 0) {
                errorMsg = "受益人为空";
                claimserror(claim.getClaimsId(), true, errorMsg, BNF);

            }
            Employee emp = empList.get(0);
            
            // 受益人是否为小孩
            String signperson = "01";
            try {
                int age = getAge(emp.getDateOfBirth(), claim.getAdmissionDate());
                if(age < 18){
                    example = new EmployeeExample();
                    example.or().andEmployeeIdEqualTo(emp.getEmployeeId()).andDependentIdIsNull();
                    empList = employeeMapper.selectByExample(example);
                    if (null == empList || empList.size() == 0) {
                        errorMsg = "主被险人为空";
                        claimserror(claim.getClaimsId(), true, errorMsg, BNF);
                        continue;
                    }
                    emp = empList.get(0);
                    signperson = "02";
                }
                
            } catch (Exception e1) {
                errorMsg = "计算受益人年龄异常！";
            }
            
            // 中间带理赔号码
            sb.append(claim.getClaimsId());
            sb.append(",");
            // 受益人类型
            sb.append("0");
            sb.append(",");
            // 自然受益人与被保人关系 
            String relationships = getRelationships(emp);
            sb.append(relationships);
            sb.append(",");
            // 自然受益人姓名
            sb.append(emp.getEmpName());
            sb.append(",");
            // 自然受益人性别
            sb.append("M".equals(emp.getGender())?"1":"F".equals(emp.getGender())?"0":"2");
            sb.append(",");
            // 自然受益人出生日期
            sb.append(emp.getDateOfBirth());
            sb.append(",");
            
            // 自然受益人证件类型
            sb.append(idTypeMap.get(emp.getIdType()));
            sb.append(",");
            // 自然受益人证件号码
            sb.append(emp.getNewIc());
            sb.append(",");
            // 自然受益级别 

            sb.append(",");
            // 自然证件有效期

            sb.append(",");
            // 自然证件为长期
            sb.append("1");
            sb.append(",");
            // 自然职业

            sb.append(",");
            // 自然住所地或工作单位地址

            sb.append(",");
            // 自然联系电话

            sb.append(",");
            // 自然国籍  CICL_COUNTRY_MAPPING
            if(StringUtils.isNotEmpty(emp.getNationality())){
                sycRefcdExample = new SycRefcdExample();
                sycRefcdExample.or().andRefgrpEqualTo("CICL_COUNTRY_MAPPING").andRefcdEqualTo(emp.getNationality());
                sycRefcdList = sycRefcdMapper.selectByExample(sycRefcdExample);
                if(null != sycRefcdList&&sycRefcdList.size()>0){
                    sb.append(sycRefcdList.get(0).getVar1());
                }
            }
            sb.append(",");
            // 自然税收居民身份类型

            sb.append(",");
            // 自然地区
            Provider provider = providerMapper.selectByPrimaryKey(claim.getProviderId());
            if(null != provider){
                sycRefcdExample = new SycRefcdExample();
                sycRefcdExample.or().andRefgrpEqualTo("CICL_AREA_MAPPING").andRefcdEqualTo(provider.getCountry());
                sycRefcdList = sycRefcdMapper.selectByExample(sycRefcdExample);
                if(null != sycRefcdList&&sycRefcdList.size()>0){
                    sb.append(sycRefcdList.get(0).getVar1());
                }
            }
            sb.append(",");
            // 姓名
            sb.append(emp.getEmpName());
            sb.append(",");
            // 本人声明
            sb.append("1");
            sb.append(",");
            // 姓（中文或拼音）

            sb.append(",");
            // 名（中文或拼音）

            sb.append(",");
            // 出生日期

            sb.append(",");
            // 现居地址（中文）

            sb.append(",");
            // 现居地址（英文或拼音）

            sb.append(",");
            // 出生地（中文）

            sb.append(",");
            // 出生地（英文或拼音）

            sb.append(",");
            // 税收居民国（地区）

            sb.append(",");
            // 纳税人识别号

            sb.append(",");
            // 如果不能提供居民国

            sb.append(",");
            // 具体原因

            sb.append(",");
            // 签署人身份
            sb.append(signperson);
            sb.append(",");

            // 领款人类型
            sb.append("0");
            sb.append(",");
            // 非自然领款人

            sb.append(",");
            // 领款人与受益人关系

            sb.append(",");
            // 领款人名称

            sb.append(",");
            // 领款人地址

            sb.append(",");
            // 经营范围

            sb.append(",");
            // 证件类型

            sb.append(",");
            // 证件类型说明

            sb.append(",");
            // 证件号码

            sb.append(",");
            // 证件有效期

            sb.append(",");
            // 证件为长期
            sb.append("1");
            sb.append(",");
            // （控股股东/实际控制人）姓名

            sb.append(",");
            // （控股股东/实际控制人）证件类型

            sb.append(",");
            // （控股股东/实际控制人）证件号码

            sb.append(",");
            // （控股股东/实际控制人）证件有效

            sb.append(",");
            // （控股股东/实际控制人）证件为长

            sb.append(",");
            // （控股股东/实际控制人）地址

            sb.append(",");
            // （法定代表人/负责人）姓名

            sb.append(",");
            // （法定代表人/负责人）证件类型

            sb.append(",");
            // （法定代表人/负责人）证件号码

            sb.append(",");
            // （法定代表人/负责人）证件有效期

            sb.append(",");
            // （法定代表人/负责人）证件为长期

            sb.append(",");
            // （授权办理业务人员）姓名

            sb.append(",");
            // （授权办理业务人员）证件类型

            sb.append(",");
            // （授权办理业务人员）证件号码

            sb.append(",");
            // （授权办理业务人员）证件有效期

            sb.append(",");
            // （授权办理业务人员）证件为长期

            sb.append(",");
            // 受益所有人信息

            sb.append(",");
            // 受益所有人姓名   TODO XXX 以下几项目为默认值   需要提供

            sb.append(",");
            // 证件类型

            sb.append(",");
            // 证件号码

            sb.append(",");
            // 证件有效期

            sb.append(",");
            // 联系地址

            sb.append(",");
            // 分配详细信息

            sb.append(",");
            // 受益比例(%)

            sb.append(",");
            // 受益金额

            sb.append(",");
            // 银行编码

            sb.append(",");
            // 银行帐户名

            sb.append(",");
            // 银行帐号

            sb.append(",");
            // 所在省

            sb.append(",");
            // 所在市

            sb.append(",");
            // 开户网点

            sb.append(",");
            // 支付方式
            sb.append("4");

            sb.append("\n");
        }
        return sb;
    }
    /**
     * 影像信息
     * @param fileName
     * @param claimsList
     * @return
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        OSS ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        ObjectListing objectListing = ossClient.listObjects(bucketName, prefix);
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        List<String> fileNameList = sums.stream().filter(e -> e.getKey().indexOf(".") != -1).map(e -> e.getKey()).collect(Collectors.toList());
        for (String fileName : fileNameList) {
            System.out.println(fileName);
            OSSObject ossObject = ossClient.getObject(bucketName, fileName);
            int index;
            byte[] bytes = new byte[1024];
            InputStream input = ossObject.getObjectContent();
            FileOutputStream downloadFile = new FileOutputStream("D:/test.tif");
            while ((index = input.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
            downloadFile.close();
            input.close();
            List<InputStream> jpgList = TiffUtil.getJpgFromTiff(ossClient.getObject(bucketName, fileName).getObjectContent());
            System.out.println();
        }
    }
    public StringBuilder createImageFile(List<ClaimsVo> claimsList) {

        StringBuilder sb = new StringBuilder();
        String errorMsg = "";
//        SFTPUtil sftpZH = new SFTPUtil(ZH_SFTP_USER, ZH_SFTP_PASSWORD, ZH_SFTP_URL, 22);// 2.0开发环节测试
        SFTPUtil sftpZH = new SFTPUtil(NY_SFTP_USER, NY_SFTP_PASSWORD, NY_SFTP_URL, 22);// 2.0开发环节测试

        sftpZH.login();
        
        OSS ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        SimpleDateFormat sf = new SimpleDateFormat("YYYYMM");
        SimpleDateFormat sf1 = new SimpleDateFormat("YYYY/MM/DD");
        
        for (ClaimsVo claim : claimsList) {
            // 文件路径 oos
            String pafix = sf.format(claim.getTransmissionDate()) + "/" + claim.getClaimsId() +"/";
            ObjectListing objectListing = ossClient.listObjects(bucketName, prefix + pafix);
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            List<String> fileNameList = sums.stream().filter(e -> e.getKey().indexOf(".") != -1).map(e -> e.getKey()).collect(Collectors.toList());
            int i = 0;
            for (String fileName : fileNameList) {
                int j = 0;
                if(fileName.endsWith(".tiff")||fileName.endsWith(".TIFF")||fileName.endsWith(".tif")||fileName.endsWith(".TIF")){
                    i++;
                    j++;
                    List<InputStream> jpgList = TiffUtil.getJpgFromTiff(ossClient.getObject(bucketName, fileName).getObjectContent());
                    for(InputStream in:jpgList){
                     // 中间带理赔号
                        sb.append(claim.getClaimsId());
                        sb.append(",");
                        // 影像类型
                        sb.append("80331010");
                        sb.append(",");
                        // 页数
                        sb.append(jpgList.size());
                        sb.append(",");
                        // 影像序号
                        sb.append(i);
                        sb.append(",");
                        // 影像名
                        sb.append(fileName.substring(fileName.lastIndexOf("/")+1,fileName.lastIndexOf(".")+1) + "_" + j + ".jpg");
                        sb.append(",");
                        // 影像扩展名
                        sb.append("jpg");
                        sb.append(",");
                        // 影像路径 
                        // 中华联合存放路径
                        String filePath = sf1.format(date)+"/"+sf.format(date)+"/"+claim.getClaimsId();
                        sb.append(pafix + filePath);
                        sb.append("\n");
                        
                        upLoad(in, fileName.substring(fileName.lastIndexOf("/")+1), sftpZH, ZHLH_PATH+"/ReturnData/Image", filePath);
                    
                    }
                }else{
                    i++;
                    // 中间带理赔号
                    sb.append(claim.getClaimsId());
                    sb.append(",");
                    // 影像类型
                    sb.append("80331010");
                    sb.append(",");
                    // 页数
                    sb.append("1");
                    sb.append(",");
                    // 影像序号
                    sb.append(i);
                    sb.append(",");
                    // 影像名
                    sb.append(fileName.substring(fileName.lastIndexOf("/")+1));
                    sb.append(",");
                    // 影像扩展名
                    sb.append(fileName.substring(fileName.lastIndexOf(".")+1));
                    sb.append(",");
                    // 影像路径 
                    // 中华联合存放路径
                    String filePath = sf1.format(date)+"/"+sf.format(date)+"/"+claim.getClaimsId();
                    sb.append(pafix + filePath);
                    sb.append("\n");
                    
                    OSSObject ossObject = ossClient.getObject(bucketName, fileName);
                    upLoad(ossObject.getObjectContent(), fileName.substring(fileName.lastIndexOf("/")+1), sftpZH, ZHLH_PATH+"/ReturnData/Image", filePath);
                }
            }
            claimserror(claim.getClaimsId(), true, errorMsg, IMG);

        }
        ossClient.shutdown(); 
        sftpZH.logout();
        return sb;
    }
    
    /**
     * 第三方支付 
     * @param fileName
     * @param claimsList
     * @return
     */
    public StringBuilder createOtherPayFile(List<ClaimsVo> claimsList) {
        StringBuilder sb = new StringBuilder();
        String errorMsg = "";

        for (ClaimsVo claim : claimsList) {
            // 中间带理赔号
            sb.append(claim.getClaimsId());
            sb.append(",");
            // 收据编号
            if("R".equals(claim.getClaimType())){
                sb.append(claim.getInvoiceId());
            }else if("E".equals(claim.getClaimType())||"M".equals(claim.getClaimType())){
                sb.append(claim.getClaimsId());
            }
            sb.append(",");
            // 第三方给付类型
            sb.append("D002");
            sb.append(",");
            // 第三方费用类型
            if("OP".equals(claim.getAdmissionType())){
                sb.append("A"); 
            }else if("IP".equals(claim.getAdmissionType())){
                sb.append("B");
            }
            sb.append(",");
            // 第三方费用金额
            sb.append(claim.getInsPrepaid());
            sb.append(",");
            // 第三方服务机构名称 TODO
            sb.append(claim.getInsPrepaidCrcd());
            sb.append(",");
            // 第三方备注

            sb.append("\n");
            claimserror(claim.getClaimsId(), true, errorMsg, COV);

        }
        return sb;
    }
    
    /**
     * 诊断类型
     * @param fileName
     * @param claimsList
     * @return
     */
    public StringBuilder createSecondaryFile(List<ClaimsVo> claimsList) {
        SycRefcdExample sycRefcdExample = null;
        List<SycRefcd> sycRefcdList = null;
        StringBuilder sb = new StringBuilder();
        String errorMsg = "";
        for (ClaimsVo claim : claimsList) {
            // 中间带理赔号
            sb.append(claim.getClaimsId());
            sb.append(",");
            // 收据编号
            if("R".equals(claim.getClaimType())){
                sb.append(claim.getInvoiceId());
            }else if("E".equals(claim.getClaimType())||"M".equals(claim.getClaimType())){
                sb.append(claim.getClaimsId());
            }
            sb.append(",");
            // 中医疾病代码
            sb.append(",");
            // 手术代码 
            sb.append(",");
            // 手术诊断类型代码 
            sb.append(",");
            // 西医疾病代码   CICL_ICD_MAPPING
            sycRefcdExample = new SycRefcdExample();
            sycRefcdExample.or().andRefgrpEqualTo("CICL_ICD_MAPPING").andRefcdEqualTo(claim.getPrimaryDiagnosis());
            sycRefcdList = sycRefcdMapper.selectByExample(sycRefcdExample);
            if(null != sycRefcdList&&sycRefcdList.size()>0){
                sb.append(sycRefcdList.get(0).getVar1());
            }else{
                sb.append("L68");
            }
            sb.append(",");
            // 西医诊断类型代码 
            sb.append("5");
            sb.append("\n");
            claimserror(claim.getClaimsId(), true, errorMsg, DIAG);
        }
        return sb;
    }
    public void upLoad(StringBuilder sb, String fileName, SFTPUtil sftpZH){
        InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
        String zhlhPath = ZHLH_PATH + "/ReturnData/Index";
        try {
            sftpZH.upload(zhlhPath, "", fileName, in);
        } catch (SftpException e1) {
            System.out.println("上传文件异常");
             e1.printStackTrace();
        }
    }
    public void upLoad(InputStream in, String fileName, SFTPUtil sftpZH, String path, String dPath){
        try {
            sftpZH.upload(path, dPath, fileName, in);
        } catch (SftpException e1) {
            System.out.println("上传文件异常");
             e1.printStackTrace();
        }
    } 
    /**
     * @param claimsId
     * @param flag
     * @param errorEmg
     */
    public void claimserror(Integer claimsId, boolean flag, String errorMsg, String reftyp){
        String refno = "";

        if(flag){
            SimpleDateFormat sf = new SimpleDateFormat("YYYYMMDD-HHmm");
            EspTxtexpsumm espTxtexpsumm = new EspTxtexpsumm();
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("payorCode", PAYORCD);
            param.put("reftyp", reftyp);
            param.put("currdt", sf.format(date));
            Integer expbatchno = claimsVoMapper.getMaxExpbatchno(param);
            refno = PAYORCD + "-" + reftyp + "-" + sf.format(date) + "-" + expbatchno;
            
            espTxtexpsumm.setPayorcd(PAYORCD);
            espTxtexpsumm.setReftyp(reftyp);
            espTxtexpsumm.setRefno(refno);
            espTxtexpsumm.setInsby(P_CURRUSR);
            espTxtexpsumm.setInsdt(date);
            espTxtexpsumm.setUpdby(P_CURRUSR);
            espTxtexpsumm.setUpddt(date);
            espTxtexpsumm.setExpsts("P");
            espTxtexpsumm.setExpdt(date);
            espTxtexpsumm.setExpcnt(1);
            espTxtexpsumm.setExpbatchno(expbatchno);
            
//            espTxtexpsummMapper.insertSelective(espTxtexpsumm);
        }
        if(StringUtil.isNotEmpty(errorMsg)){
            EspTxtexp espTxtexp = new EspTxtexp();
            espTxtexp.setPayorcd(PAYORCD);
            espTxtexp.setReftyp(reftyp);
            espTxtexp.setRefno(refno);
            espTxtexp.setRecno(1L);
            espTxtexp.setInsby(P_CURRUSR);
            espTxtexp.setInsdt(date);
            espTxtexp.setUpdby(P_CURRUSR);
            espTxtexp.setUpddt(date);
            espTxtexp.setPuid(claimsId.toString());
//            espTxtexp.setTextline(textline);
            espTxtexp.setErrmsg(errorMsg);
//            espTxtexpMapper.insertSelective(espTxtexp);
        }
    }
    public void updateRsvamtTracking(ClaimsVo claim){
        RsvamtTracking rsvamtTracking = new RsvamtTracking();
        rsvamtTracking.setUploadDate(date);
        rsvamtTracking.setClaimsId(claim.getClaimsId());
        rsvamtTracking.setClaimsStatus(claim.getClaimsStatus());
        rsvamtTracking.setTransactionDate(claim.getTransactionDate());
        rsvamtTrackingMapper.updateByPrimaryKeySelective(rsvamtTracking);
    }
    
    
    public String getRelationships(Employee emp){
        String relationship = emp.getRelationship();
        String relationships = "";
        if("0".equals(relationship)){
            relationships = "00";
        }else if("1".equals(relationship)){
            relationships = "01";
        }else if("2".equals(relationship)){
            relationships = "05";
        }else if("3".equals(relationship)){
            if("M".equals(emp.getGender())){
                relationships = "03";
            }else{
                relationships = "04";
            }
        }else if("99".equals(relationship)){
            relationships = "30";
        }
        return relationships;
    }

    /**
     * 生日到出险日期之间的年龄
     * @param birthDay
     * @param admissionDate
     * @return
     * @throws Exception
     */
    public static int getAge(Date birthDay, Date admissionDate) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.setTime(admissionDate);
        if (cal.before(birthDay)) { // 出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR); // 当前年份
        int monthNow = cal.get(Calendar.MONTH); // 当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); // 当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth; // 计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth)
                    age--;// 当前日期在生日之前，年龄减一
            } else {
                age--;// 当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

}
